﻿using LiteDB;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyWPF.Models.UserManagement
{
    public class UserHelper_LiteDb :IUser
    {
        private LiteDatabase DB;
        private ILiteCollection<UserContext> Users;

        public UserContext User { get; set; }

        /// <summary>
        /// 初始化数据库
        /// </summary>
        public void LoadDB(UserDbContext UserDb)
        {
            if (!Directory.Exists(UserDb.Path)) // 如果文件夹不存在
            {
                Directory.CreateDirectory(UserDb.Path); // 创建文件夹
            }

            //创建数据库
            string Filename = Path.Combine(UserDb.Path, UserDb.DbName);
            DB = new LiteDatabase("Filename=" + Filename + ";Password=" + UserDb.Password);
            //新建表
            Users = DB.GetCollection<UserContext>("Users");
            AddUser(new UserContext()
            {
                UserName = "admin",
                Password = "123456",
                Power = UserPower.Administrator,
                PowerLevel = 4000,
                RegistrationTime = DateTime.Now,
                Remarks = "系统默认账户"
            });

            //用户初始化
            User = new UserContext();
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="User"></param>
        /// <returns></returns>
        public bool Login(UserContext _User)
        {
            var result = Users.Find(x => x.UserName == _User.UserName && x.Password == _User.Password);
            if (result.ToArray().Length > 0)
            {
                //登录成功后将Errors置为0，并给User赋值
                UserContext UpDateUser = result.FirstOrDefault();
                if (UpDateUser != null)
                {
                    UpDateUser.Errors = 0;
                    ModifyUser(UpDateUser);
                }
                User = UpDateUser;
                return true;
            }
            else
            {
                //登录失败需要将Errors++
                result = Users.Find(x => x.UserName == _User.UserName);
                UserContext UpDateUser = result.FirstOrDefault();
                if (UpDateUser != null)
                {
                    UpDateUser.Errors++;
                    UpDateUser.ErrorTime = DateTime.Now;
                    ModifyUser(UpDateUser);
                }
                return false;
            }
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        public bool AddUser(UserContext User)
        {
            //如果之前就存在同名账号就不允许继续创建
            if (GetUser_UserName(User).Rows.Count == 0)
            {
                Users.Insert(User);
                return true;
            }
            else
            {
                return false;
            }
        }


        /// <summary>
        /// 修改用户
        /// </summary>
        /// <param name="OldInfo"></param>
        /// <param name="NewInfo"></param>
        public void ModifyUser(UserContext User)
        {
            User._id = GetUserStruct_UserName(User)[0]._id;
            Users.Update(User._id, User);
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="User"></param>
        public void RemoveUser(UserContext User)
        {
            Users.DeleteMany(d => d.UserName == User.UserName);
        }

        /// <summary>
        /// 输入用户，通过用户等级返回所有小于等于该等级的用户
        /// </summary>
        /// <param name="User"></param>
        /// <returns></returns>
        public DataTable GetUser_Level(UserContext User)
        {
            var result = Users.Find(x => x.PowerLevel <= User.PowerLevel).ToArray();
            return UserContextToDataTable(result);
        }

        public DataTable GetUser_UserName(UserContext User)
        {
            var result = Users.Find(x => x.UserName == User.UserName);
            return UserContextToDataTable(result.ToArray());
        }
        public DataTable GetUser_Password(UserContext User)
        {
            var result = Users.Find(x => x.UserName == User.UserName && x.Password == User.Password);
            return UserContextToDataTable(result.ToArray());
        }

        public UserContext[] GetUserStruct_Level(UserContext User)
        {
            return Users.Find(x => x.PowerLevel >= User.PowerLevel).ToArray();
        }

        public UserContext[] GetUserStruct_UserName(UserContext User)
        {
            return Users.Find(x => x.UserName == User.UserName).ToArray();
        }

        public UserContext[] GetUserStruct_Password(UserContext User)
        {
            return Users.Find(x => x.UserName == User.UserName && x.Password == User.Password).ToArray();
        }

        private DataTable UserContextToDataTable(UserContext[] Users)
        {
            DataTable dataTable = new DataTable();

            dataTable.Columns.Add("用户", typeof(string));
            dataTable.Columns.Add("权限", typeof(string));
            dataTable.Columns.Add("注册时间", typeof(DateTime));
            dataTable.Columns.Add("上一次登录时间",typeof(DateTime));
            dataTable.Columns.Add("备注", typeof(string));

            foreach(UserContext item in Users)
            {
                DataRow newDataRow = dataTable.NewRow();
                newDataRow["用户"] = item.UserName;
                newDataRow["权限"] = item.Power;
                newDataRow["注册时间"] = item.RegistrationTime;
                newDataRow["上一次登录时间"] = item.LastLoginTime;
                newDataRow["备注"] = item.Remarks;
                dataTable.Rows.Add(newDataRow);
            }

            return dataTable;
        }

        
    }
}
